﻿define(["common"], function (common) {
    
    common.factory("authenticationDialogs", [
        "$q",
        "$http",
        "$rootScope",
        "signInService",
        "authenticationService",
        function ($q, $http, $rootScope, signInService, authenticationService) {
                    
            var $this = {
                showSignIn: function () {
                    var deferred = $q.defer();
                    setTimeout(function () {
                        $rootScope.$apply(function () {
                            signInService.showDialog();
                        });
                    }, 50);

                    authenticationService.getDefers("signIn").push(deferred);
                    return deferred.promise;
                }
            };

            return $this;
        }
    ]);

    // intercept the HTTP to handler the 401 error (unauthorized)
    common.config(["$provide", "$httpProvider", function ($provide, $httpProvider) {
        $provide.factory("authenticationInterceptor", ["$q", "$injector", function ($q, $injector) {
            return {
                'responseError': function (response) {
                    if (response.status === 401) {
                        var authenticationDialogs = $injector.get('authenticationDialogs');
                        var $http = $injector.get("$http");
                        return authenticationDialogs.showSignIn()
                            .then(function () {
                                return $http(response.config);
                            },
                            function () {
                                $q.reject(response);
                            });
                    }
                    return $q.reject(response);
                }
            };
        }]);

        $httpProvider.interceptors.push('authenticationInterceptor');
    }]);
});